﻿using System;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using Realtime;  // 由 Protos/chat.proto 生成的命名空间

namespace GrpcChatClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 1. 建立到 gRPC 服务的 Channel（开发环境 HTTP/2 明文）
            using var channel = GrpcChannel.ForAddress("http://localhost:5001", new GrpcChannelOptions
            {
                MaxReceiveMessageSize = 4 * 1024 * 1024,
                MaxSendMessageSize = 4 * 1024 * 1024
            });

            // 2. 创建 ChatService 客户端 Stub
            var client = new ChatService.ChatServiceClient(channel);

            // 3. 准备鉴权头，key 必须是 "authorization"
            var headers = new Metadata
            {
                { "authorization", "Bearer demo-token" }
            };

            // 4. 发起双向流调用，带上鉴权头
            using var call = client.Chat(headers);

            // 5. 并行启动发送和接收任务
            var sendTask = Task.Run(async () =>
            {
                Console.Write("请输入用户名：");
                var user = Console.ReadLine() ?? "User";

                while (true)
                {
                    var line = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        // 输入空行则结束上行流
                        await call.RequestStream.CompleteAsync();
                        break;
                    }

                    // 发送 ChatMessage
                    await call.RequestStream.WriteAsync(new ChatMessage
                    {
                        User = user,
                        Message = line,
                        Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    });
                }
            });

            var receiveTask = Task.Run(async () =>
            {
                try
                {
                    // 不断从下行流读取消息
                    await foreach (var msg in call.ResponseStream.ReadAllAsync())
                    {
                        Console.WriteLine($"[{msg.User}] {msg.Message}");
                    }
                }
                catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
                {
                    Console.WriteLine("服务器已关闭流");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"接收异常：{ex.Message}");
                }
            });

            // 等待发送和接收都完成
            await Task.WhenAll(sendTask, receiveTask);
        }
    }
}
